/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Test.java
 *
 * Created on 08.mai.2012, 01:25:08
 */

package GUI;


import Ibutton.DeviceHandler.Hygrochron;
import Ibutton.DeviceHandler.Thermochron;
import com.dalsemi.onewire.OneWireException;
import com.dalsemi.onewire.container.OneWireContainer;
import java.awt.Desktop;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;

/**
 *
 * @author Baardsen
 */
public class GraphViewer extends javax.swing.JFrame {

    private Hygrochron hygrochron;
    private Thermochron thermochron;
    private DefaultListModel graph_list;
    private Boolean HYGROCHRON = false;
    private String CUSTOM_GRAPH_FOLDER;
  
    /**
     * Setting up a new graph viewer. This can be used to view current mission graphs and view custom ones.
     * @param owc
     * OneWireContainer - With the current mission you want to display
     * @throws OneWireException
     * @throws Exception
     */
    public GraphViewer(Object owc) throws OneWireException, Exception {
        initComponents();

        try{
            hygrochron = (Hygrochron) owc;
            HYGROCHRON = true;
        }catch(Exception e){
            thermochron = (Thermochron) owc;
        }

        CUSTOM_GRAPH_FOLDER = System.getProperty("user.dir")+"\\Mission\\CustomGraph";
        setup();
        setSize(1024, 720);
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
    
    private void setupCustomList(){
        graph_list = new DefaultListModel();
  
        File dir = new File(CUSTOM_GRAPH_FOLDER);
        String[] children = dir.list();
        if(HYGROCHRON){
            for(int i=0;i<children.length;i++){
                if(children[i].contains(hygrochron.getAlternativeName())){
                    if(!children[i].endsWith(".ps"))
                    graph_list.addElement(CUSTOM_GRAPH_FOLDER+"\\"+(String)children[i]);
                }               
            }
        }else{
            for(int i=0;i<children.length;i++){
                if(children[i].contains(thermochron.getAlternativeName())){
                     if(!children[i].endsWith(".ps"))
                    graph_list.addElement(CUSTOM_GRAPH_FOLDER+"\\"+(String)children[i]);
                }
            }

        }
        customGraphs.setModel(graph_list);

    }

    private void createCustomFolder(){
        new File(CUSTOM_GRAPH_FOLDER).mkdir();
    }

    private void setup() throws OneWireException, Exception{
        graph_list = new DefaultListModel();
        createCustomFolder();
         if(HYGROCHRON){
            setTitle(hygrochron.getAlternativeName());
            hygrochron.readHumidity();
            hygrochron.readTemperatures();
            hygrochron.generateGraph();

            graph_list.addElement(hygrochron.HUMIDITY_GRAPH_NAME);
            graph_list.addElement(hygrochron.TEMPERATURE_GRAPH_NAME);
            graph_list.addElement(hygrochron.TEMP_HUM_GRAPH_NAME);

            graphs.setModel(graph_list);
            setupCustomList();
         }else{
            setTitle(thermochron.getAlternativeName());
            thermochron.readTemperatures();
            thermochron.generateGraph();
            graph_list.addElement(thermochron.TEMPERATURE_GRAPH_NAME);
            graphs.setModel(graph_list);
            setupCustomList();
         }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        picture = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        deleteCustom = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        graphs = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        customGraphs = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        picture.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        picture.setText("jLabel3");
        picture.setToolTipText("Here you will see the graph you selected.");
        picture.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        picture.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jScrollPane3.setViewportView(picture);

        jSplitPane1.setRightComponent(jScrollPane3);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel2.setText("Current mission graphs:");

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        deleteCustom.setText("Delete");
        deleteCustom.setToolTipText("Delete a selected graph.");
        deleteCustom.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteCustomActionPerformed(evt);
            }
        });

        jButton2.setText("Refresh");
        jButton2.setToolTipText("Refresh the lists.");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Make Custom Graph");
        jButton1.setToolTipText("Make a new custom graph.");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(deleteCustom)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(deleteCustom)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        graphs.setToolTipText("This is the current mission graphs.");
        graphs.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                graphsValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(graphs);

        jLabel1.setText("Custom graphs:");

        customGraphs.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        customGraphs.setToolTipText("Here you will find custom graphs you have created.");
        customGraphs.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                customGraphsValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(customGraphs);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 313, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jSplitPane1.setLeftComponent(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1184, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated

    }//GEN-LAST:event_formWindowActivated

    private void graphsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_graphsValueChanged
        try {
            BufferedImage image;
                image = ImageIO.read(new File((String) graphs.getSelectedValue()));
                picture.setIcon(new ImageIcon(image));
            } catch (IOException ex) {
           
            }
    }//GEN-LAST:event_graphsValueChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if(HYGROCHRON){
           
            try {
                new CustomGraph(hygrochron, CUSTOM_GRAPH_FOLDER);
                
            } catch (Exception ex) {
                Logger.getLogger(GraphViewer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else{
            try {
                new CustomGraph(thermochron, CUSTOM_GRAPH_FOLDER);
                
            } catch (Exception ex) {
                Logger.getLogger(GraphViewer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

           
        
    }//GEN-LAST:event_jButton1ActionPerformed
    private String getType(String path){
        String type = "";
        if(path.endsWith(".svg")){
          type = ".svg";
        }else{
           type = ".png";
        }
        return type;
    }
    private void displayPNG(){
        try {
            BufferedImage image;
            image = ImageIO.read(new File((String) customGraphs.getSelectedValue()));
            picture.setIcon(new ImageIcon(image));
        } catch (IOException ex) {
            Box.Message("An error occoured while trying to display the image, the file might be corrupt.");
        }
    }
    private void displaySVG(String path) throws URISyntaxException, IOException{
        if(Desktop.isDesktopSupported())
            Browser.displayURL(path);
        else
            Box.Message("Desktop is not supported on your computer, so I cannot render your file.");
    }
    private void customGraphsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_customGraphsValueChanged
        try {
                String type = getType((String) customGraphs.getSelectedValue());
                if(type==".png"){
                   displayPNG();
                }else if(type==".svg"){
                    displaySVG((String) customGraphs.getSelectedValue());
                }else{
                    Box.Message("Sorry I cannot render this type of a file.");
                }

            } catch (Exception ex) {

            }
    }//GEN-LAST:event_customGraphsValueChanged

    private void deleteCustomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteCustomActionPerformed
        new File((String)customGraphs.getSelectedValue()).delete();
        if(Box.Confirm("Are you sure you want to delete: " + (String)customGraphs.getSelectedValue() + "?", "Delete")==Box.YES){
            Box.Message((String)customGraphs.getSelectedValue()+ " has been deleted.");
            setupCustomList();
        }
    }//GEN-LAST:event_deleteCustomActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        setupCustomList();
    }//GEN-LAST:event_jButton2ActionPerformed

  

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList customGraphs;
    private javax.swing.JButton deleteCustom;
    private javax.swing.JList graphs;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JLabel picture;
    // End of variables declaration//GEN-END:variables

}
